const { Service } = require('egg')
// const { tableToList } = require('../utils/tools');
const cheerio = require('cheerio')

const iconv = require('iconv-lite') // 导入iconv-lite模块

module.exports = class SinfoService extends Service {
  /**
   * * 学籍卡片信息
   * @return {Object} *
   */
  async table() {
    const Cookie = this.ctx.state.Cookie
    const apiUrl2 = `${this.ctx.state.baseUrl}/cssfjw/STU_BaseInfoAction.do?hidOption=InitData&menucode_current=S10101`
    const res = await this.ctx.curl(apiUrl2, {
      method: 'GET',
      headers: {
        Cookie,
        Referer: 'http://58.20.34.197:10115/cssfjw/student/stu.xsxj.xjda.jbxx.html?menucode=S10101',
        'Content-Type': 'application/x-www-form-urlencoded',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36',
      },
      timeout: 10000,
    })
    // console.log('res', res);
    const info = {}
    const gbkString = iconv.decode(res.data, 'gbk')
    // console.log('gbkString', gbkString);

    if (res.status === 200) {
      try {
        // 拿到数据并处理数据
        const $ = cheerio.load(gbkString)
        const info2 = $('*') // 获取info元素
        // console.log('info', info);
        // console.log('info', info.toString);
        const dataList = [] // 初始化表格数组
        // 获取 学院,专业,学制,班级,学号,姓名,性别,年级
        info2.find('yxb,lqzy,xz,bjmc,yhxh,xm,xb,rxnj').each((i, e) => {
          dataList[i] = $(e).text()
        });
        // 解构交换位置
        [dataList[0], dataList[2]] = [dataList[2], dataList[0]];
        [dataList[1], dataList[4]] = [dataList[4], dataList[1]];
        [dataList[2], dataList[6]] = [dataList[6], dataList[2]];
        [dataList[3], dataList[4]] = [dataList[4], dataList[3]];
        [dataList[4], dataList[5]] = [dataList[5], dataList[4]];
        [dataList[5], dataList[7]] = [dataList[7], dataList[5]]

        // console.log('dataList_1', dataList_1);
        // console.log('dataList_2', dataList_2);
        // const dataList = dataList1.concat(dataList2)
        const tableList = ['院系', '专业', '学制', '班级', '学号', '姓名', '性别', '年级']
        const result = {}
        tableList.forEach((key, i) => {
          const value = dataList[i]
          result[key] = value
        })
        return result
      } catch (err) {
        console.log('err', err)
        throw err
      }
    }
    return info
  }
}
